package com.sun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.dto.OutstoreDto;
import com.sun.entity.Outstore;
import com.sun.entity.OutstoreDetail;
import com.sun.entity.Store;
import com.sun.mapper.OutstoreMapper;
import com.sun.service.OutstoreDetailService;
import com.sun.service.OutstoreService;
import com.sun.service.StoreService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Project: hospitalDrugInformationManagement
 * @Author: 86178
 * @Date: 2023/3/21 15:30
 * @FileName: OutstoreServiceImpl
 * @Description: ""
 */
@SuppressWarnings("all")
@Service
public class OutstoreServiceImpl extends ServiceImpl<OutstoreMapper, Outstore> implements OutstoreService {
    @Autowired
    private OutstoreDetailService outstoreDetailService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private OutstoreMapper outstoreMapper;

    @Override
    public void saveWithOutstoreDetail(OutstoreDto outstoreDto) {
        //保存出库的基本信息，操作outstore，执行insert操作
        this.save(outstoreDto);
        //保存入库表单目
        List<OutstoreDetail> outstoreDetails = outstoreDto.getOutstoreDetails();
        outstoreDetails.stream().map((item) -> {
            item.setOutboundId(outstoreDto.getOutboundId());
            return item;
        }).collect(Collectors.toList());

        outstoreDetailService.saveBatch(outstoreDetails);
        //加入出库单的药品，应该在库存中减相应的数量
        //update outstore_detail set num = num - 10 where
        List<Store> storeList = outstoreDetails.stream().map(item -> {
            Store store = new Store();
            Store store1 = storeService.getById(item.getStoreId());
            store.setId(store1.getId());
            store.setDrugNumber(store1.getDrugNumber() - item.getNum());
            return store;
        }).collect(Collectors.toList());
        storeService.updateBatchById(storeList);
    }

    @Override
    public void updateWithOutstoreDetail(OutstoreDto outstoreDto) {
        //先更新出库单单头的信息
        this.updateById(outstoreDto);
        //再更新出库单单目的信息
        //先把出库单目查询出来和新的比较如果存在就更新，不存在就新增，新的数据没有就删除
        //查询历史数据
        LambdaQueryWrapper<OutstoreDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OutstoreDetail::getOutboundId, outstoreDto.getOutboundId());
        List<OutstoreDetail> oldData = outstoreDetailService.list(lambdaQueryWrapper);
        //新的数据
        List<OutstoreDetail> dtoOutstoreDetails = outstoreDto.getOutstoreDetails();
        //进行比较
        // 遍历新数据列表
        for (OutstoreDetail newData : dtoOutstoreDetails) {
            // 是否需要新增
            boolean flag = true;
            // 在历史数据列表中的位置
            int i = 0;
            // 遍历历史数据列表
            for (i = 0; i < oldData.size(); i++) {
                OutstoreDetail oldInstoreDetail = oldData.get(i);
                boolean exist = false; // 是否存在于新数据列表中
                // 比较历史数据和新数据
                if (newData.getId() != null && newData.getId().equals(oldInstoreDetail.getId())) {
                    // 需要更新
                    flag = false;
                    outstoreDetailService.updateById(newData);
                    break;
                }

            }
            if (flag) {
                // 需要新增
                newData.setOutboundId(outstoreDto.getOutboundId());
                outstoreDetailService.save(newData);
            }
        }

        for (OutstoreDetail oldItem : oldData) {
            boolean exist = false; // 是否存在于新数据列表中
            // 判断历史数据是否存在于新数据列表中
            for (OutstoreDetail item : dtoOutstoreDetails) {
                if (oldItem.getId().equals(item.getId())) {
                    exist = true;
                    break;
                }
            }
            if (!exist) {
                // 需要删除
                outstoreDetailService.removeById(oldItem.getId());
            }
        }
    }

    @Override
    public IPage<OutstoreDto> selectOutstoreDtoListPage(Page<OutstoreDto> page, String userName, String addr, LocalDateTime startTime, LocalDateTime endTime) {
        return outstoreMapper.selectOutstoreDtoListPage(page, userName, addr, startTime, endTime);
    }

    @Override
    public OutstoreDto getByIdWithOutstoreDetail(Long id) {
        OutstoreDto outstoreDto = new OutstoreDto();
        //查询入库单基本信息，从outstore表查询
        Outstore outstore = this.getById(id);
        BeanUtils.copyProperties(outstore, outstoreDto);

        //查询当前入库单对应的药品信息，从outstore_detail表查询
        LambdaQueryWrapper<OutstoreDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OutstoreDetail::getOutboundId, outstore.getOutboundId());
        List<OutstoreDetail> outstoreDetails = outstoreDetailService.list(lambdaQueryWrapper);
        outstoreDto.setOutstoreDetails(outstoreDetails);

        return outstoreDto;
    }

    @Override
    public void batchDeleteByIds(List<Long> ids) {
        //如果可以删除，先删除入库单头表中的数据---outstore
        this.removeByIds(ids);
        //delete from outstore_detail where outbound_id in (1,2,3)
        LambdaQueryWrapper<OutstoreDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(OutstoreDetail::getOutboundId, ids);
        //删除关系表中的数据----outstore_detail
        outstoreDetailService.remove(lambdaQueryWrapper);

    }
}
